package com.wceManage.commons.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wceManage.commons.bean.WeixinUserInfo;


/**
 * 微信工具类
 * @author huangheng
 * @date 20190513
 *
 */
public class WeixinUtil2 {


	
	
	/**
     * 获取用户信息
     * 
     * @param accessToken 接口访问凭证
     * @param openId 用户标识
     * @return WeixinUserInfo
     */
    public static WeixinUserInfo getUserInfo(String wx_appid, String wx_secret, String openId, String accesstoken) {
        WeixinUserInfo weixinUserInfo = null;
        
        // 获取access_token
      
        String access_token = accesstoken;
     	if ("".equals(accesstoken) || accesstoken == null) {
     				
     		String 	s = weChatSendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid=" + wx_appid + "&secret=" + wx_secret);
     		System.out.println("s="+s);	
     		JSONObject a = JSON.parseObject(s);
     		access_token = a.getString("access_token");
     		accesstoken = access_token;
     	}
     	System.out.println("accesstoken="+accesstoken);		
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accesstoken+"&GetOpenId="+openId+"&lang=zh_CN";
    	
        // 获取用户信息
        JSONObject jsonObject = JSON.parseObject(weChatSendGet(requestUrl,null));
       
        if (null != jsonObject) {
            try {
                weixinUserInfo = new WeixinUserInfo();
                // 用户的标识
                weixinUserInfo.setOpenId(jsonObject.getString("GetOpenId"));
                // 关注状态（1是关注，0是未关注），未关注时获取不到其余信息
               // weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
                // 用户关注时间
                weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
                // 昵称
                weixinUserInfo.setNickname(jsonObject.getString("nickname"));
                // 用户的性别（1是男性，2是女性，0是未知）
               // weixinUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                weixinUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                weixinUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                weixinUserInfo.setCity(jsonObject.getString("city"));
                // 用户的语言，简体中文为zh_CN
                weixinUserInfo.setLanguage(jsonObject.getString("language"));
                // 用户头像
                weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
            } catch (Exception e) {
            	System.out.println("获取用户信息失败:"+jsonObject);
            	e.printStackTrace();
               
            }
        }
        return weixinUserInfo;
    }
		
    
	//微信
	public static String weChatSendGet(String url, String param) {
			String result = "";
			BufferedReader in = null;
			try {
				String urlNameString = url + "?" + param;
				URL realUrl = new URL(urlNameString);
				// 打开和URL之间的连接
				URLConnection connection = realUrl.openConnection();
				// 设置通用的请求属性
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				// 建立实际的连接
				connection.connect();
				// 定义 BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
			} catch (Exception e) {
				System.out.println("发送GET请求出现异常！" + e);
				e.printStackTrace();
			}
			// 使用finally块来关闭输入流
			finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return EscapeUtil.unescape(result);
		}
}
